<template>
  <div class="page-root">
    <BasePanel>
      <div style="display: flex;">
    <BaseSearch
        :search="searchProps"
        @searchData="updateTable"
        @resetData="updateTable"
      />
      <a-button style="margin-left: 20px;" type="primary" icon="download" ghost @click="handleExport">导出</a-button>
  </div>
      <div class="table-top-wrap">
        <div class="table-title">
          <span>列表</span>
        </div>
        <span class="primary" @click="edit_list" v-if="isbool === false"
          >屏蔽</span
        >
        <div v-else>
          <a-checkbox
            class="chack_box"
            v-model="item.isbool"
            v-for="(item, index) in columns_copy"
            :key="index"
          >
            {{ item.title }}
          </a-checkbox>
          <span class="primary" @click="isbool = false">关闭</span>
        </div>
        <div style="margin-left: 10px">
          合计消耗：<span style="color: skyblue"> {{ useAmount }}</span>
        </div>
      </div>
      <BaseTable
        bordered
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :scroll="{ x: 1000 }"
      >
        <template slot="billStatus" slot-scope="{ record, index }">
          <div>
            <a-select
              @change="billStatus_change(record)"
              v-if="record.isbool"
              v-model="record.billStatus"
              placeholder="请选择"
            >
              <a-select-option :value="1">账单无误</a-select-option>
              <a-select-option :value="0">初始账单</a-select-option>
            </a-select>
            <div v-else @click="record.isbool = true">
              <a-button class="btn_card" v-if="record.billStatus - 0 === 1">
                账单无误
              </a-button>
              <a-button v-else class="btn_card2"> 初始账单 </a-button>
            </div>
          </div>
        </template>
        <template slot="operation" slot-scope="{ record }">
          <span class="primary" @click="handleEdit(record)">修改账单</span>
        </template>
      </BaseTable>
      <div v-show="dataSource.length > 0" class="page-footer">
        <BasePagination :page-key.sync="pageKey" :get-list="tableInit" />
      </div>
    </BasePanel>
    <adjust
      :time="time"
      :visible="adjustShow"
      :id="id"
      :loanId="loanId"
      :default="defaultObj"
      @success="successForm"
      @close="closeAdjust"
    ></adjust>
  </div>
</template>

<script>
import { searchProps, columns } from "./option.js";
import * as Ajax from "@/api/bill";
import adjust from "./adjust.vue";
import { ajaxDownload } from '@/utils/export.js';
export default {
  components: {
    adjust,
  },
  data() {
    return {
      searchProps,
      searchForm: {},
      columns,
      loading: false,
      dataSource: [],
      pageKey: {
        pageSize: 10,
        total: 1,
        current: 1,
      },
      money: "",
      defaultObj: {},
      adjustShow: false,
      id: "",
      isbool: false,
      columns_copy: [],
      useAmount: 0,
      time: "",
      loanId: "",
    };
  },
  watch: {
    columns_copy: {
      handler(newColumns) {
        this.columns = newColumns.filter((item) => item.isbool);
      },
      deep: true,
    },
  },
  created() {
    this.columns_copy = this.columns;
    this.tableInit();
    this.getSelect();
  },
  methods: {
    async handleExport() {
      this.loading = true
      const { current, pageSize } = this.pageKey;
      const params = { pageNum: current, pageSize, ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + ' 00:00:00';
        params.endTime = params.time[1] + ' 23:59:59';
      } else {
        params.startTime =''
        params.endTime = ''
      }
      delete params.time;
      const queryString = new URLSearchParams(params).toString();
      await ajaxDownload(`/web/loan/bill/list/excel?${queryString}`, 'get')(params);
      this.loading = false
    },
    edit_list() {
      this.isbool = true;
    },
    handleEdit(record) {
      const { loanId, times, id } = record;
      this.loanId = loanId;
      this.id = id;
      this.time = times;
      this.adjustShow = true;
    },
    successForm() {
      this.tableInit();
      // this.closeForm();
    },
    closeAdjust() {
      this.adjustShow = false;
      this.id = "";
    },
    getSelect() {
      Ajax.getChannelSelect().then((res) => {
        if (res.success) {
          searchProps[0].selectOptions = Array.isArray(res.data)
            ? res.data.map((it) => ({
                ...it,
                label: it.channelName,
                value: it.id,
              }))
            : [];
        }
      });
    },
    // applyuse
    updateTable(params = {}) {
      this.searchForm = { ...params };
      this.pageKey = this.$options.data().pageKey;
      this.tableInit();
    },

    // 当天日期
    getFormattedDate(type) {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0");
      const day = String(today.getDate()).padStart(2, "0");

      if (type === "start") {
        return `${year}-${month}-${day} 00:00:00`;
      } else if (type === "end") {
        return `${year}-${month}-${day} 23:59:59`;
      }
    },
    timestampToTime(timestamp) {
      var date = new Date(timestamp); // 时间戳是以秒为单位，需要乘以1000转换为毫秒
      var year = date.getFullYear();
      var month = ("0" + (date.getMonth() + 1)).slice(-2);
      var day = ("0" + date.getDate()).slice(-2);

      return year + "-" + month + "-" + day;
    },
    async get_billlistsum(params) {
      const res = await Ajax.loanbilllistsum(params);
      if (res.success) {
        console.log(res);
        this.useAmount = res.data.useAmount;
      }
    },
    async billStatus_change(record) {
      const res = await Ajax.loaneditbillStatus({
        id: record.id,
        billStatus: record.billStatus,
      });
      if (res.success) {
        this.tableInit();
      }
    },
    // table 初始化
    tableInit() {
      this.loading = true;
      const { current, pageSize } = this.pageKey;
      const params = { pageNum: current, pageSize, ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + " 00:00:00";
        params.endTime = params.time[1] + " 23:59:59";
      } else {
        // params.startTime = this.getFormattedDate('start');
        // params.endTime = this.getFormattedDate('end');
      }
      delete params.time;

      Ajax.loanbilllist(params)
        .then((res) => {
          const { data, totalCount } = res;
          // console.log('123',data)
          data.forEach((item) => {
            if (item.time) {
              item.times = item.time;
              item.time = this.timestampToTime(item.time - 0);
            }
            item.isbool = false;
          });

          this.dataSource = Array.isArray(data) ? data : [];
          // console.log('参数',this.dataSource )
          this.pageKey.total = totalCount;
          this.get_billlistsum(params);
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 16px;
}

.table-top-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.table-img {
  max-height: 20px;
  max-width: 100px;
}

.table-title {
  flex: 1;

  span {
    line-height: 32px;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before {
      content: "";
      display: block;
      width: 3px;
      height: 18px;
      background-color: #1890ff;
      margin-right: 8px;
      position: relative;
      top: -1px;
    }
  }
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;

  & > button {
    margin-left: 12px;

    &:first-child {
      margin-left: 0;
    }
  }
}
.chack_box {
  margin: 0 2px !important;
  padding: 2px !important;
  font-size: 12px;
}
.btn_card{
  border: 0 !important;
  // margin-left: 22px;
  text-align: center;
  width: 90px;
  padding: 3px 0;
  background-color: skyblue;
  color: #fff;
  border-radius: 10px;
}
.btn_card2{
  border: 0 !important;
  //  margin-left: 22px;
  text-align: center;
  width: 90px;
  padding: 3px 0;
  background-color: #9a8df0;
  color: #fff;
  border-radius: 10px;
}
</style>
